import Vue from 'vue'
import VueRouter from 'vue-router'
import store  from "../store"
import login from '../components/login/login'
import register from '../components/login/register'
import admin from "../components/admin/index"
import search from "../components/admin/search"
import personalCenter from "../components/admin/personalCenter"
import article from "../components/article/index"
import xiugai from "../components/article/xiugai"
import book from "../components/book/index"
import newchapter from "../components/book/newchapter"
import xiugaichapter from "../components/book/xiugaichapter"
import chapterlist from "../components/chapter/chapterlist"
import readpage from "../components/chapter/readpage"

Vue.use(VueRouter)

  const routes = [
    {
      path:'/',redirect:"/admin"
    },
    {
      path:"*",
      component:()=>import("@/components/common/err.vue")
    },
    {
      path:"/login",component:login
    },
    {
      path:"/register",component:register
    },
    {
      path:"/admin",component:admin
    },
    {
      path:"/search",component:search
    },
    {
      path:"/personalCenter",component:personalCenter
    },
    {
      path:"/articlecreate",component:article
    },
    {
      path:"/article/xiugai/:articleid",component:xiugai
    },
    {
      path:"/book/:articleid",component:book
    },
    {
      path:"/newchapter/:articleid",component:newchapter
    },
    {
      path:"/xiugaichapter",component:xiugaichapter
    },
    {
      path:"/chapterlist/:articleid",component:chapterlist
    },
    {
      path:"/readpage/:chapterid",component:readpage
    },
    {
      path:"/chat/chat",component:()=>import("@/components/chat/chat")
    },
    {
      path:"/chat/chats",component:()=>import("@/components/chat/chats")
    },
    {
      path:"/chat/chatlist",component:()=>import("@/components/chat/chatlist")
    },
]

const router = new VueRouter({
  routes,
  scrollBehavior (to, from, savedPosition) {
    return { x: 0, y: 0}
  }
})

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //to 将要跳转到那个路由
  //from 来至哪个路由
  //next 表示放行，有两种方式 next()  next("/home")

  if (to.path === "/login"||to.path === "/register") {
      return next()
  } else {
      //获取在登陆时返回数据里面保存在内存中的token值
      const tokenStr = sessionStorage.getItem("cookie")
      // console.log(tokenStr)
      if (!tokenStr||!store.state.readerdata) {
          return next("/login")
      } else {
          next()
      }
  }
})


export default router
